package com.ht.dsp.impl;

import com.ht.aems.util.SocketManager;
import com.ht.dsp.RtdbRefresher;
import hhh.utils.FileUtil;
import org.apache.log4j.Logger;

import java.io.FileInputStream;
import java.net.InetSocketAddress;
import java.rmi.RemoteException;
import java.util.Properties;

/**
 * Created by IntelliJ IDEA.
 *
 * @author Dong Shufeng
 *         Date: 2011-3-22
 */
public class ScadaDataUpdator_nari extends AbstractScadaUpdator {
    private static Logger log = Logger.getLogger(ScadaDataUpdator_nari.class);

    private int failedNum = 0;
    String[] serverIps; //rtdb ips
    int[] ports; //rtdb ports
    int currentServer = 0;//current using index of rtdb

    public ScadaDataUpdator_nari() throws RemoteException {
        super();
        setInstance("nari");
        //get fes server's ips and port
        String f = FileUtil.getRootDirectory() + "/_config/ip.properties";
        Properties properties = new Properties();
        try {
            properties.load(new FileInputStream(f));
            serverIps = new String[4];
            ports = new int[4];
            for (int i = 1; i <= 4; i++) {
                String server = properties.getProperty("RtdbServer.ip" + i).trim();//assuming that the first ip is prime
                int port = Integer.parseInt(properties.getProperty("RtdbServer.ip" + i + ".port"));
                serverIps[i - 1] = server;
                ports[i - 1] = port;
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("No RtdbServer.ip properties are found!");
            serverIps = new String[]{};
        }
        SocketManager.closeSocket(RTDB_SERVER);
        SocketManager.unregister(RTDB_SERVER);
        if (currentServer < serverIps.length)
            SocketManager.register(RTDB_SERVER, new InetSocketAddress(serverIps[currentServer], ports[currentServer]));
    }

    @Override
    public String getMeasureId(String input) {
        String[] idAndType = input.split("[:]");//todo:
        int idLength = idAndType[0].length();
        int a = 10 - idLength;
        int typeLength = idAndType[1].length();
        int b = 4 - typeLength;
        char[] chars = new char[14];
        for (int i = 0; i < a; i++)
            chars[i] = '0';
        System.arraycopy(idAndType[0].toCharArray(), 0, chars, a, idLength);
        for (int i = 0; i < b; i++)
            chars[i + a + idLength] = '0';
        System.arraycopy(idAndType[1].toCharArray(), 0, chars, a + idLength + b, typeLength);
        return new String(chars);
    }

    public boolean update() {
        boolean r = order();
        if (!r) {
            log.warn("Updating scada data failed!");
            failedNum++;
            if (failedNum >= failNumAllowed) {
                SocketManager.closeSocket(RTDB_SERVER);
                currentServer++;
                if (currentServer >= serverIps.length)
                    currentServer = 0;
                if (currentServer < serverIps.length)
                    SocketManager.register(RTDB_SERVER, new InetSocketAddress(serverIps[currentServer], ports[currentServer]));
            }
            return false;
        } else {
            failedNum = 0;
            RtdbRefresher.saveRawDataToRtdb(getInstance());
            return true;
        }
    }

    public void setDatasourceIpPort(String ip, int port) throws RemoteException {
        SocketManager.closeSocket(RTDB_SERVER);
        int index = 0;
        for (String serverIp : serverIps) {
            if (serverIp.equals(ip))
                break;
            index++;
        }
        currentServer = index;
        if (currentServer < serverIps.length) {
            SocketManager.register(RTDB_SERVER, new InetSocketAddress(serverIps[currentServer], ports[currentServer]));
            log.info("Nari Rtdb server is changed to: " + ip);
        }
    }
}
